const { formatTime } = require('../../utils/util')
Page({
  data: {
    nvabarData: {
      title: '',
      transmit: ''
    },
    isRecording: false, // 是否正在录制
    devicePosition: 'back', // 摄像头位置：'front'前置，'back'后置
    videoPath: '', // 录制完成后的视频路径
    recordDuration: 0, // 录制时长（秒）
    cameraContext: null, // 相机上下文
    timer: null, // 计时器
    maxDuration: 300,// 最大录制时长（5分钟）
    audioPlaying: false,
    audioCurrentTime: 0,// 播放器实际时间
    audioDuration: 100,
    audioDisplayTime: '00:00',        // 显示的时间（与Slider同步）
    audioSliderValue: 0,        // Slider的显示值
    isAudioSeeking: false,      // 是否正在拖动
    audioSeekTarget: 0,         // 跳转目标时间
    audioSeekTimer: null,       // 跳转防抖定时器
    audioContext: null,
    audioUpdateInterval: null,
    item: {}
  },

  onLoad(options) {
    console.log('onLoad')
    const { item } = options;
    const data = JSON.parse(item)
    this.setData({
      'nvabarData.title': data.title + '录制'
    })
    this.setData({
      item: data,
    })
    this.setScreen()
    this.initCamera();
    this.initAudio()
  },

  onUnload() {
    console.log('onUnload')
    this.cleanup();
    this.stopAudio()
  },
  onShow() {
    console.log('onShow')
    this.setData({
      isRecording: false
    })
  },
  onHide() {
    console.log('onHide', this.data.audioContext)
    this.stopAudio()
    this.cleanup();
  },

  setScreen() {
    // 设置屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
      success: function (res) {
        console.log('保持屏幕常亮设置成功')
      }
    })
  },

  // 清理资源
  cleanup() {
    if (this.data.isRecording) {
      this.stopRecording();
    }
    // 关闭常亮
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },
  initAudio() {
    // 创建音频上下文
    this.setData({
      audioContext: wx.createInnerAudioContext()
    }, () => {

      // 设置音频事件监听
      this.data.audioContext.onPlay(() => {
        console.log('音频开始播放');
        this.setData({
          audioPlaying: true,
        });
        this.startAudioProgressUpdate();
      });

      this.data.audioContext.onPause(() => {
        console.log('音频暂停');
        this.setData({
          audioPlaying: false
        });
        this.stopAudioProgressUpdate();
      });

      this.data.audioContext.onStop(() => {
        console.log('音频播放停止');
        this.setData({
          audioPlaying: false,
          audioCurrentTime: 0,
          audioDisplayTime: formatTime(0),
          audioSliderValue: 0
        });
        this.stopAudioProgressUpdate();
        if (this.data.audioSeekTimer) {
          clearTimeout(this.data.audioSeekTimer);
        }
      });
      this.data.audioContext.onEnded(() => {
        console.log('音频播放结束');
        this.setData({
          audioPlaying: false,
          audioCurrentTime: 0,
          audioDisplayTime: formatTime(0),
          audioSliderValue: 0
        });
        this.stopAudioProgressUpdate();
      });

      this.data.audioContext.onError((res) => {
        console.error('音频播放错误:', res.errMsg);
      });

      this.data.audioContext.onCanplay(() => {
        console.log('音频可以播放');
        // 获取音频时长
        setTimeout(() => {
          this.setData({
            audioDuration: Math.floor(this.data.audioContext.duration),
          });
        }, 500);
      });

      // 音频跳转完成事件
      this.data.audioContext.onSeeked(() => {
        console.log('音频跳转完成');
        // 跳转完成后，同步显示时间和实际时间
        this.setData({
          isAudioSeeking: false,
          audioCurrentTime: this.data.audioSeekTarget,
          audioDisplayTime: formatTime(this.data.audioSeekTarget)
        });
      });

      // 音频时间更新事件
      this.data.audioContext.onTimeUpdate(() => {
        if (!this.data.isAudioSeeking) {
          const currentTime = Math.floor(this.data.audioContext.currentTime);
          this.setData({
            audioCurrentTime: currentTime,
            audioDisplayTime: formatTime(currentTime),
            audioSliderValue: currentTime
          });
        }
      });
    });


  },

  // 初始化相机
  initCamera() {
    const cameraContext = wx.createCameraContext();
    this.setData({
      cameraContext: cameraContext,
      videoPath: '', // 清空之前的视频
      recordDuration: 0
    });
  },

  // 开始录制
  startRecording() {
    const { cameraContext, maxDuration } = this.data;
    // 开始录制
    cameraContext.startRecord({
      timeout: maxDuration, // 设置最大录制时长
      success: (res) => {
        console.log('开始录制成功');
        this.setData({ isRecording: true });

        // 开始计时
        this.startTimer();

        wx.showToast({
          title: '开始录制',
          icon: 'none'
        });
        this.startAudio()
      },
      fail: (err) => {
        console.error('开始录制失败：', err);
        wx.showToast({
          title: '录制失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 开始播放音频
  startAudio() {
    this.stopAudio()
    // 加载音频
    this.data.audioContext.src = this.data.item.src;
    this.data.audioContext.autoplay = true;
  },

  stopAudio() {
    // 停止当前音频
    if (this.data.audioContext) {
      this.data.audioContext.stop();
    }
  },
  // 停止录制
  stopRecording() {
    console.log('停止录制----')
    // 停止计时器
    this.stopTimer();
    try {
      const { cameraContext } = this.data;
      cameraContext.stopRecord({
        success: (res) => {
          console.log('录制完成', res.tempVideoPath);
          this.setData({
            isRecording: false,
            videoPath: res.tempVideoPath
          });
          wx.showToast({
            title: '录制完成',
            icon: 'success'
          });
          this.stopAudio()
        },
        fail: (err) => {
          console.error('停止录制失败：', err);
          this.setData({ isRecording: false });
          wx.showToast({
            title: '停止录制失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.log('停止录制失败', error)
      this.setData({ isRecording: false });
    }

  },

  // 切换摄像头
  switchCamera() {
    if (this.data.isRecording) {
      wx.showToast({
        title: '录制中不能切换摄像头',
        icon: 'none'
      });
      return;
    }

    const newPosition = this.data.devicePosition === 'back' ? 'front' : 'back';
    this.setData({
      devicePosition: newPosition
    });
  },

  // 重新录制
  reRecord() {
    this.setData({
      videoPath: '',
      recordDuration: 0
    });

    // 重新初始化相机
    this.initCamera();

    wx.showToast({
      title: '可重新录制',
      icon: 'none'
    });
  },

  // 保存到相册
  saveToAlbum() {
    const { videoPath } = this.data;

    if (!videoPath) {
      wx.showToast({
        title: '没有可保存的视频',
        icon: 'none'
      });
      return;
    }

    // 先申请相册权限
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success: () => {
        // 权限已获得，保存视频
        this.doSaveVideo(videoPath);
      },
      fail: (err) => {
        console.error('授权失败：', err);
        // 引导用户手动开启权限
        wx.showModal({
          title: '提示',
          content: '需要您授权保存到相册功能',
          confirmText: '去授权',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              wx.openSetting(); // 打开设置页面
            }
          }
        });
      }
    });
  },

  // 执行保存视频
  doSaveVideo(filePath) {
    wx.saveVideoToPhotosAlbum({
      filePath: filePath,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail: (err) => {
        console.error('保存失败：', err);

        let errorMsg = '保存失败';
        if (err.errMsg.includes('deny')) {
          errorMsg = '保存权限被拒绝，请在设置中开启';
        }

        wx.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 开始计时器
  startTimer() {
    this.recordStartTime = Date.now();
    this.setData({ recordDuration: 0 });

    this.data.timer = setInterval(() => {
      const duration = Math.floor((Date.now() - this.recordStartTime) / 1000);
      this.setData({ recordDuration: formatTime(duration) });

      // 检查是否达到最大时长
      if (duration >= this.data.maxDuration) {
        this.stopRecording();
      }
    }, 1000);
  },

  // 停止计时器
  stopTimer() {
    console.log('停止计时器')
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.data.timer = null;
    }
  },

  // 相机错误处理
  cameraError(e) {
    console.error('相机错误：', e.detail);
    wx.showModal({
      title: '相机错误',
      content: '无法启动相机，请检查权限或重启小程序',
      showCancel: false
    });
  },


  // 播放音频
  playAudio: function () {
    if (this.data.audioPlaying) {
      this.data.audioContext.pause();
    } else {
      this.data.audioContext.play();
    }
  },

  // 音频进度更新
  startAudioProgressUpdate: function () {
    this.stopAudioProgressUpdate(); // 先停止之前的定时器
  },


  // 停止音频进度更新
  stopAudioProgressUpdate: function () {
    if (this.data.audioUpdateInterval) {
      clearInterval(this.data.audioUpdateInterval);
      this.data.audioUpdateInterval = null;
    }
  },
  // 音频滑块拖动中 - 实时更新显示
  onAudioSliderChanging: function (e) {
    const value = e.detail.value;
    this.setData({
      audioSliderValue: value,
      audioDisplayTime: formatTime(value),
      isAudioSeeking: true
    });
  },
  // 音频滑块变化
  onAudioSliderChange: function (e) {
    const value = e.detail.value;
    // 清除之前的跳转定时器
    if (this.data.audioSeekTimer) {
      clearTimeout(this.data.audioSeekTimer);
    }
    this.setData({
      audioSeekTarget: value,
    });

    // 使用防抖，延迟执行跳转
    this.data.audioSeekTimer = setTimeout(() => {
      if (this.data.audioContext) {
        this.data.audioContext.seek(value);
      }
    }, 50);
  },

  // 返回
  backFun() {
    if (this.data.isRecording || this.data.videoPath) {
      wx.showModal({
        content: '检测到您正在录制或者当前的录像未保存，是否仍要退出？',
        success: res => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
      return
    }
    wx.navigateBack();
  },
});